﻿using System.IO;
using System.Reflection;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interop;
using System.Windows.Media;
using HappyBa.Core;
using HappyBa.Core.Interfaces;
using HappyBa.Core.Reporting;
using HappyBa.Dialogs;
using HappyBa.Localization;
using LightInject;
using Mnk.Library.CodePlex;
using Mnk.Library.Common.SaveLoad;
using Mnk.Library.WpfControls;
using ServicesRegistrar = HappyBa.Code.ServicesRegistrar;

namespace HappyBa
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        private readonly LazyDialog<AboutDialog> aboutDialog;
        private readonly LazyDialog<SettingsDialog> settingsDialog;
        private readonly IFullReportGenerator report;

        private readonly ConfigurationSerializer<Config> serializer = new ConfigurationSerializer<Config>(Path.Combine(Folders.UserRootFolder, "configuration.config"));
        public IServiceContainer Container { get; private set; }
        public Config Config { get; set; }

        public MainWindow()
        {
            RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnly;
            Container = ServicesRegistrar.Register(serializer);
            Config = Container.GetInstance<Config>();
            InitializeComponent();
            if (!OneInstance.MainWindow.Init(this)) return;
            Title = GetCaption();
            ThreadPool.QueueUserWorkItem(o => Container.GetInstance<IAutoUpdater>().TryUpdate());
            Container.GetInstance<IThemesManager>().Load("Default.xaml");
            var currentConfig = Config.Current; 
            if (currentConfig!=null && Config.Settings.Connection.CollectOnStartup)
            {
                Loaded += (o,e) => Container.GetInstance<IDataCollector>().Collect();
            }
            report = Container.GetInstance<IFullReportGenerator>();
            settingsDialog = new LazyDialog<SettingsDialog>(BuildSettingsDialog);
            aboutDialog = new LazyDialog<AboutDialog>(BuildAboutDialog);
        }
        
        private static string GetCaption()
        {
            var ver = Assembly.GetExecutingAssembly().GetName().Version;
            return string.Format("{0} {1}.{2}", HappyBaLang.Caption, ver.Major, ver.Minor);
        }

        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            serializer.Save(Container.GetInstance<Config>());
            Container.GetInstance<ILogsSender>().SendIfNeed();
            Container.Dispose();
        }

        private void TabChanged(object sender, SelectionChangedEventArgs e)
        {
            switch (Tabs.SelectedIndex)
            {
                case 0:
                case 1:
                    ((TabItem) Tabs.Items[1]).DataContext = Container.GetInstance<IDataCache>().Metrics;
                    break;
            }
        }

        public override void Dispose()
        {
            base.Dispose();
            aboutDialog.Dispose();
            settingsDialog.Dispose();
        }

        private AboutDialog BuildAboutDialog()
        {
            return new AboutDialog { Owner = this };
        }

        private SettingsDialog BuildSettingsDialog()
        {
            return new SettingsDialog
            {
                DataContext = Config.Settings.Connection,
                Owner = this
            };
        }

        private void AboutClick(object sender, RoutedEventArgs e)
        {
            aboutDialog.Value.ShowDialog();
        }

        private void ExitClick(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void SettingsClick(object sender, RoutedEventArgs e)
        {
            settingsDialog.Value.ShowDialog();
        }

        private void RefreshClick(object sender, RoutedEventArgs e)
        {
            settingsDialog.Value.CollectClick(sender, e);
        }

        private void ExportClick(object sender, RoutedEventArgs e)
        {
            report.GenerateFullReport();
        }


    }
}
